<template>
  <el-dialog
    :model-value="visible"
    class="create-task-dialog"
    width="1400px"
    align-center
    :close-on-click-modal="false"
    :show-close="false"
    :before-close="handleClose"
    @update:model-value="(value: boolean) => emit('update:visible', value)"
  >
    <template #header>
      <div class="dialog-header-wrapper">
        <div class="dialog-header-title">新建任务</div>
        <div class="dialog-header-actions">
          <el-button @click="handleClose">关闭</el-button>
          <el-button
            type="primary"
            :loading="saving"
            :disabled="!canCreate"
            @click="handleCreate"
          >
            确认
          </el-button>
        </div>
      </div>
    </template>

    <div class="create-task">
      <div class="detail-body">
        <div class="primary-column">
          <div class="detail-header">
            <div class="header-top">
              <div class="status-tags">
                <el-tag
                  v-if="formData.status"
                  :type="getStatusTypeWrapper(formData.status) as any"
                  size="small"
                >
                  {{ getStatusTextWrapper(formData.status) }}
                </el-tag>
                <el-tag
                  v-if="formData.priority"
                  :type="getPriorityTypeWrapper(formData.priority) as any"
                  size="small"
                >
                  {{ getPriorityTextWrapper(formData.priority) }}
                </el-tag>
                <el-tag
                  v-if="formData.task_type"
                  size="small"
                  type="info"
                >
                  {{ getTypeTextWrapper(formData.task_type) }}
                </el-tag>
              </div>
            </div>

            <div class="title-section" ref="titleFieldRef">
              <div class="field-label">
                <span>任务标题</span>
                <span class="required">*</span>
              </div>
              <el-input
                v-model="formData.title"
                placeholder="请输入任务标题"
                maxlength="200"
                show-word-limit
                size="large"
                class="title-input"
                :class="{ 'field-error': fieldErrors.title }"
                @input="clearFieldErrorWrapper('title')"
              />
              <div v-if="fieldErrors.title" class="error-message">{{ fieldErrors.title }}</div>
            </div>
          </div>

          <section class="section-card tabs-card">
            <el-tabs v-model="contentTab" class="content-tabs">
              <el-tab-pane label="任务描述" name="description">
                <div class="tab-content-wrapper">
                  <EnhancedRichTextEditor
                    v-model="formData.description"
                    placeholder="请描述任务内容..."
                    :min-height="400"
                  />
                </div>
              </el-tab-pane>

              <el-tab-pane label="验收标准" name="acceptance">
                <div class="tab-content-wrapper">
                  <el-input
                    v-model="formData.acceptance_criteria"
                    type="textarea"
                    placeholder="请填写验收标准"
                    :rows="6"
                    maxlength="2000"
                    show-word-limit
                    resize="vertical"
                  />
                </div>
              </el-tab-pane>
            </el-tabs>
          </section>

          <!-- 关联部分 - 放在任务描述下方 -->
          <section class="section-card associations-card">
            <div class="associations-header">
              <div class="associations-title">关联</div>
            </div>
            <div class="associations-content">
              <el-tabs v-model="associationSubTab" type="border-card" class="association-sub-tabs">
                <!-- 关联需求子页签 -->
                <el-tab-pane label="关联需求" name="requirements">
                  <div class="sub-tab-content">
                    <div class="tab-header">
                      <div class="header-info">
                        <span class="item-count">已选择需求（{{ selectedRequirements.length }}）</span>
                      </div>
                      <div class="header-actions">
                        <el-button
                          type="primary"
                          size="small"
                          @click="handleAddRequirement"
                        >
                          <el-icon><Plus /></el-icon>
                          添加需求
                        </el-button>
                      </div>
                    </div>

                    <div class="items-list">
                      <el-table
                        v-if="selectedRequirements.length > 0"
                        :data="selectedRequirements"
                        size="default"
                        border
                        stripe
                        style="width: 100%"
                      >
                        <el-table-column prop="title" label="需求标题" min-width="200" show-overflow-tooltip />
                        <el-table-column prop="status" label="状态" width="120">
                          <template #default="{ row }">
                            <el-tag 
                              :type="getRequirementStatusType(row.status) as any" 
                              size="small"
                              :style="{ 
                                backgroundColor: getRequirementStatusColor(row.status),
                                borderColor: getRequirementStatusColor(row.status),
                                color: '#fff'
                              }"
                            >
                              {{ getRequirementStatusName(row.status) }}
                            </el-tag>
                          </template>
                        </el-table-column>
                        <el-table-column prop="priority" label="优先级" width="100">
                          <template #default="{ row }">
                            <el-tag 
                              :type="getRequirementPriorityType(row.priority) as any" 
                              size="small"
                              :style="{ 
                                backgroundColor: getRequirementPriorityColor(row.priority),
                                borderColor: getRequirementPriorityColor(row.priority),
                                color: '#fff'
                              }"
                            >
                              {{ getRequirementPriorityName(row.priority) }}
                            </el-tag>
                          </template>
                        </el-table-column>
                        <el-table-column prop="assignee_name" label="负责人" width="140" show-overflow-tooltip>
                          <template #default="{ row }">
                            <UserDisplay
                              v-if="row.assignee_id"
                              :user-id="row.assignee_id"
                              :user-name="row.assignee_name"
                              :show-avatar="true"
                              size="small"
                            />
                            <span v-else style="color: #909399;">未分配</span>
                          </template>
                        </el-table-column>
                        <el-table-column label="操作" width="120" fixed="right">
                          <template #default="{ row }">
                            <el-button
                              link
                              type="danger"
                              size="small"
                              @click="handleRemoveRequirement(row)"
                            >
                              移除
                            </el-button>
                          </template>
                        </el-table-column>
                      </el-table>
                      <el-empty v-else description="暂无关联需求，点击'添加需求'进行关联" :image-size="80" />
                    </div>
                  </div>
                </el-tab-pane>

                <!-- 关联缺陷子页签 -->
                <el-tab-pane label="关联缺陷" name="defects">
                  <div class="sub-tab-content">
                    <div class="tab-header">
                      <div class="header-info">
                        <span class="item-count">已选择缺陷（{{ selectedDefects.length }}）</span>
                      </div>
                      <div class="header-actions">
                        <el-button
                          type="primary"
                          size="small"
                          @click="handleAddDefect"
                        >
                          <el-icon><Plus /></el-icon>
                          添加缺陷
                        </el-button>
                      </div>
                    </div>

                    <div class="items-list">
                      <el-table
                        v-if="selectedDefects.length > 0"
                        :data="selectedDefects"
                        size="default"
                        border
                        stripe
                        style="width: 100%"
                      >
                        <el-table-column prop="title" label="缺陷标题" min-width="200" show-overflow-tooltip />
                        <el-table-column prop="status" label="状态" width="100">
                          <template #default="{ row }">
                            <el-tag :type="getDefectStatusType(row.status) as any" size="small">
                              {{ getDefectStatusName(row.status) }}
                            </el-tag>
                          </template>
                        </el-table-column>
                        <el-table-column prop="severity" label="严重程度" width="100">
                          <template #default="{ row }">
                            <el-tag :type="getDefectSeverityType(row.severity) as any" size="small">
                              {{ getDefectSeverityName(row.severity) }}
                            </el-tag>
                          </template>
                        </el-table-column>
                        <el-table-column prop="priority" label="优先级" width="90">
                          <template #default="{ row }">
                            <el-tag :type="getDefectPriorityType(row.priority) as any" size="small">
                              {{ getDefectPriorityName(row.priority) }}
                            </el-tag>
                          </template>
                        </el-table-column>
                        <el-table-column label="操作" width="120" fixed="right">
                          <template #default="{ row }">
                            <el-button
                              link
                              type="danger"
                              size="small"
                              @click="handleRemoveDefect(row)"
                            >
                              移除
                            </el-button>
                          </template>
                        </el-table-column>
                      </el-table>
                      <el-empty v-else description="暂无关联缺陷，点击'添加缺陷'进行关联" :image-size="80" />
                    </div>
                  </div>
                </el-tab-pane>
              </el-tabs>
            </div>
          </section>
        </div>

        <aside class="side-column">
          <section class="info-card">
            <div class="info-card-title">基础字段</div>
            <div class="info-form-group" v-if="defaultParentId && defaultParentName">
              <label class="info-label">父任务</label>
              <div class="parent-info-display">
                <el-tag type="info" size="default">
                  <el-icon><ArrowLeft /></el-icon>
                  {{ defaultParentName }}
                </el-tag>
                <span class="parent-hint">（新建的子任务）</span>
              </div>
            </div>
            <div class="info-form-group" ref="statusFieldRef">
              <label class="info-label">状态 <span class="required">*</span></label>
              <el-select
                v-model="formData.status"
                placeholder="请选择状态"
                size="default"
                :class="{ 'field-error': fieldErrors.status }"
                @change="clearFieldErrorWrapper('status')"
              >
                <el-option
                  v-for="option in statusOptions"
                  :key="option.value"
                  :value="option.value"
                  :label="option.label"
                />
              </el-select>
              <div v-if="fieldErrors.status" class="error-message">{{ fieldErrors.status }}</div>
            </div>
            <div class="info-form-group">
              <label class="info-label">优先级</label>
              <el-select
                v-model="formData.priority"
                placeholder="请选择优先级"
                size="default"
              >
                <el-option
                  v-for="option in priorityOptions"
                  :key="option.value"
                  :value="option.value"
                  :label="option.label"
                />
              </el-select>
            </div>
            <div class="info-form-group">
              <label class="info-label">任务类型</label>
              <el-select
                v-model="formData.task_type"
                placeholder="请选择任务类型"
                size="default"
              >
                <el-option
                  v-for="option in typeOptions"
                  :key="option.value"
                  :value="option.value"
                  :label="option.label"
                />
              </el-select>
            </div>
            <div class="info-form-group" ref="projectFieldRef">
              <label class="info-label">所属项目 <span class="required">*</span></label>
              <el-select
                v-model="formData.project_id"
                placeholder="请选择项目"
                size="default"
                :class="{ 'field-error': fieldErrors.project_id }"
                @change="clearFieldErrorWrapper('project_id')"
              >
                <el-option
                  v-for="option in projectOptions"
                  :key="option.value"
                  :value="option.value"
                  :label="option.label"
                />
              </el-select>
              <div v-if="fieldErrors.project_id" class="error-message">{{ fieldErrors.project_id }}</div>
            </div>
          </section>

          <section class="info-card">
            <div class="info-card-title">人员</div>
            <div class="info-form-group">
              <label class="info-label">报告人 <span class="required">*</span></label>
              <el-select
                v-model="formData.reporter_id"
                placeholder="请选择报告人"
                size="default"
                filterable
                :class="{ 'field-error': fieldErrors.reporter_id }"
                @change="clearFieldErrorWrapper('reporter_id')"
              >
                <el-option
                  v-for="user in users"
                  :key="user.id"
                  :value="user.id"
                  :label="user.name"
                >
                  <UserDisplay
                    :user-id="user.id"
                    :user-name="user.name"
                    :show-avatar="true"
                    size="small"
                  />
                </el-option>
              </el-select>
              <div v-if="fieldErrors.reporter_id" class="error-message">{{ fieldErrors.reporter_id }}</div>
            </div>
            <div class="info-form-group">
              <label class="info-label">负责人</label>
              <el-select
                v-model="formData.assignee_id"
                placeholder="请选择负责人"
                size="default"
                filterable
              >
                <el-option
                  v-for="user in users"
                  :key="user.id"
                  :value="user.id"
                  :label="user.name"
                >
                  <UserDisplay
                    :user-id="user.id"
                    :user-name="user.name"
                    :show-avatar="true"
                    size="small"
                  />
                </el-option>
              </el-select>
            </div>
          </section>

          <section class="info-card">
            <div class="info-card-title">时间与工时</div>
            <div class="info-form-group">
              <label class="info-label">开始时间</label>
              <el-date-picker
                v-model="formData.start_date"
                type="datetime"
                placeholder="选择开始时间"
                size="default"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm"
              />
            </div>
            <div class="info-form-group">
              <label class="info-label">截止时间</label>
              <el-date-picker
                v-model="formData.due_date"
                type="datetime"
                placeholder="选择截止时间"
                size="default"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm"
                :disabled="!formData.start_date"
                :disabled-date="(time: Date) => formData.start_date ? time < new Date(formData.start_date) : false"
              />
            </div>
            <div class="info-form-group">
              <label class="info-label">预计工时</label>
              <el-input-number
                v-model="formData.estimated_hours"
                placeholder="请输入预计工时"
                size="default"
                :min="0"
                :precision="2"
                :step="0.5"
                style="width: 100%"
              />
            </div>
          </section>

          <section class="info-card">
            <div class="info-card-title">标签</div>
            <div class="info-form-group">
              <el-select
                v-model="formData.tags"
                multiple
                filterable
                allow-create
                default-first-option
                collapse-tags
                collapse-tags-tooltip
                placeholder="请选择标签或输入新标签"
                size="default"
              >
                <el-option
                  v-for="tag in commonTagOptions"
                  :key="tag"
                  :label="tag"
                  :value="tag"
                />
              </el-select>
            </div>
          </section>
        </aside>
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { requirementAPI } from '@/api/requirements'
import { getUserDetail } from '@/api/users'
import { ElMessage } from 'element-plus'
import { Plus, ArrowLeft } from '@element-plus/icons-vue'
import { TaskCreateForm, TaskStatus, TaskPriority, TaskType } from '@/types/task'
import { taskAPI } from '@/api/task'
import EnhancedRichTextEditor from '@/components/common/EnhancedRichTextEditor.vue'
import { useRequirementStates } from '@/composables/useRequirementStates'
import { useRequirementOptions } from '@/composables/useRequirementOptions'
import { useTaskStates } from '@/composables/useTaskStates'
import UserDisplay from '@/components/ui/UserDisplay.vue'

// Props
const props = defineProps<{
  visible: boolean
  currentUserId: string
  defaultProjectId?: string
  defaultParentId?: string
  defaultParentName?: string
  defaultRequirementId?: string
  defaultVersionIds?: string[]
  statusOptions: { value: TaskStatus; label: string }[]
  priorityOptions: { value: TaskPriority; label: string }[]
  typeOptions: { value: TaskType; label: string }[]
  projectOptions: { value: string; label: string }[]
  users: { id: string; name: string }[]
  commonTagOptions: string[]
}>()

// Emits
const emit = defineEmits<{
  'update:visible': [value: boolean]
  'created': [taskId: string]
}>()

// Form Data
const formData = reactive<{
  title: string
  description?: string
  task_type: TaskType
  status: TaskStatus
  priority: TaskPriority
  project_id: string
  reporter_id: string
  assignee_id?: string
  start_date?: string
  due_date?: string
  estimated_hours?: number
  tags?: string[]
  acceptance_criteria?: string
  requirement_id?: string
  version_ids?: string[]
}>({
  title: '',
  description: '',
  task_type: 'feature',
  status: 'todo',
  priority: 'medium',
  project_id: props.defaultProjectId || '',
  reporter_id: props.currentUserId || '',
  assignee_id: '',
  start_date: '',
  due_date: '',
  estimated_hours: 0,
  tags: [],
  acceptance_criteria: '',
  requirement_id: props.defaultRequirementId || '',
  version_ids: props.defaultVersionIds || []
})

// Field Errors
const fieldErrors = reactive<Record<string, string>>({})

// UI State
const saving = ref(false)
const contentTab = ref('description')
const associationSubTab = ref('requirements')

// Selected Items
const selectedRequirements = ref<any[]>([])
const selectedDefects = ref<any[]>([])

// Refs
const titleFieldRef = ref<HTMLElement | null>(null)
const statusFieldRef = ref<HTMLElement | null>(null)
const projectFieldRef = ref<HTMLElement | null>(null)

// Computed Properties
const canCreate = computed(() => {
  return !!(formData.title && formData.status && formData.project_id && formData.reporter_id)
})

// Methods
const resetForm = () => {
  // Reset form data
  Object.assign(formData, {
    title: '',
    description: '',
    task_type: 'feature',
    status: 'todo',
    priority: 'medium',
    project_id: props.defaultProjectId || '',
    reporter_id: props.currentUserId || '',
    assignee_id: '',
    start_date: '',
    due_date: '',
    estimated_hours: 0,
    tags: [],
    acceptance_criteria: '',
    requirement_id: props.defaultRequirementId || '',
    version_ids: props.defaultVersionIds || []
  })

  // Clear errors
  Object.keys(fieldErrors).forEach(key => delete fieldErrors[key])

  // Reset selected items
  selectedRequirements.value = []
  selectedDefects.value = []

  // Reset tabs
  contentTab.value = 'description'
  associationSubTab.value = 'requirements'
}

const validateForm = (): boolean => {
  const errors: Record<string, string> = {}

  if (!formData.title?.trim()) {
    errors.title = '任务标题不能为空'
  }

  if (!formData.status) {
    errors.status = '请选择任务状态'
  }

  if (!formData.project_id) {
    errors.project_id = '请选择所属项目'
  }

  if (!formData.reporter_id) {
    errors.reporter_id = '请选择报告人'
  }

  Object.assign(fieldErrors, errors)
  return Object.keys(errors).length === 0
}

const handleCreate = async () => {
  if (!validateForm()) {
    // Scroll to first error
    const firstErrorField = Object.keys(fieldErrors)[0]
    const errorRef = {
      title: titleFieldRef,
      status: statusFieldRef,
      project_id: projectFieldRef
    }[firstErrorField]
    if (errorRef?.value) {
      errorRef.value.scrollIntoView({ behavior: 'smooth', block: 'center' })
    }
    return
  }

  try {
    saving.value = true

    // Create task data
    const createData: TaskCreateForm = {
      title: formData.title,
      description: formData.description,
      task_type: formData.task_type,
      status: formData.status,
      priority: formData.priority,
      project_id: formData.project_id,
      reporter_id: formData.reporter_id,
      assignee_id: formData.assignee_id,
      start_date: formData.start_date,
      due_date: formData.due_date,
      estimated_hours: formData.estimated_hours || undefined,
      tags: formData.tags,
      requirement_id: formData.requirement_id || undefined,
      version_ids: formData.version_ids && formData.version_ids.length > 0 ? formData.version_ids : undefined
    }

    // Call API to create task
    const response = await taskAPI.createTask(createData)

    // Emit created event with task ID
    const taskId = (response as any).data?.id || (response as any).data?._id || (response as any).id || ''
    if (taskId) {
      emit('created', taskId)
    }

    // Show success message
    ElMessage.success('任务创建成功')
    
    // Close dialog and reset form
    handleClose()
  } catch (error: any) {
    const message = error.message || '创建失败'
    ElMessage.error(message)
  } finally {
    saving.value = false
  }
}

const handleClose = () => {
  emit('update:visible', false)
  resetForm()
}

const handleAddRequirement = () => {
  // TODO: Implement requirement selection dialog
}

const handleRemoveRequirement = (requirement: any) => {
  const index = selectedRequirements.value.findIndex(item => item.id === requirement.id)
  if (index > -1) {
    selectedRequirements.value.splice(index, 1)
    // 如果移除的是默认关联的需求，清空 requirement_id
    if (formData.requirement_id === requirement.id) {
      formData.requirement_id = ''
    }
  }
}

const handleAddDefect = () => {
  // TODO: Implement defect selection dialog
}

const handleRemoveDefect = (defect: any) => {
  const index = selectedDefects.value.findIndex(item => item.id === defect.id)
  if (index > -1) {
    selectedDefects.value.splice(index, 1)
  }
}

// Utility Methods - 从状态管理系统动态获取
const { getStatusType: getStatusTypeFromComposable } = useTaskStates()
const getStatusTypeWrapper = (status: TaskStatus): string => {
  if (!status) return 'info'
  return getStatusTypeFromComposable(status)
}

const getStatusTextWrapper = (status: TaskStatus): string => {
  const option = props.statusOptions.find(opt => opt.value === status)
  return option?.label || status
}

const getPriorityTypeWrapper = (priority: TaskPriority): string => {
  const priorityMap: Record<string, string> = {
    lowest: 'info',
    low: 'info',
    medium: '',
    high: 'warning',
    urgent: 'danger',
    critical: 'danger',
    blocker: 'danger'
  }
  return priorityMap[priority] || ''
}

const getPriorityTextWrapper = (priority: TaskPriority): string => {
  const option = props.priorityOptions.find(opt => opt.value === priority)
  return option?.label || priority
}

const getTypeTextWrapper = (type: TaskType): string => {
  const option = props.typeOptions.find(opt => opt.value === type)
  return option?.label || type
}

// Clear field error
const clearFieldErrorWrapper = (field: string) => {
  if (fieldErrors[field]) {
    delete fieldErrors[field]
  }
}

// 使用 composables 获取需求状态和优先级的映射
const { getStateName: getRequirementStateName, getStateColor: getRequirementStateColor, getStatusType: getRequirementStatusTypeFromState, loadStates: loadRequirementStates } = useRequirementStates()
const { getPriorityName: getRequirementPriorityNameFromOptions, getPriorityColor: getRequirementPriorityColorFromOptions } = useRequirementOptions()

// 在组件挂载时加载需求状态数据
onMounted(async () => {
  await loadRequirementStates()
})

// 需求状态相关方法
const getRequirementStatusType = (status: string) => {
  return getRequirementStatusTypeFromState(status) || 'info'
}

const getRequirementStatusName = (status: string) => {
  return getRequirementStateName(status) || status
}

const getRequirementStatusColor = (status: string) => {
  return getRequirementStateColor(status)
}

// 需求优先级相关方法
const getRequirementPriorityType = (priority: string) => {
  // 根据优先级返回对应的 tag type
  const priorityMap: Record<string, string> = {
    'lowest': 'info',
    'low': 'info',
    'medium': '',
    'high': 'warning',
    'urgent': 'danger',
    'critical': 'danger',
    'blocker': 'danger'
  }
  return priorityMap[priority?.toLowerCase()] || 'warning'
}

const getRequirementPriorityName = (priority: string) => {
  return getRequirementPriorityNameFromOptions(priority) || priority
}

const getRequirementPriorityColor = (priority: string) => {
  return getRequirementPriorityColorFromOptions(priority)
}
const getDefectStatusType = (_status: string) => 'danger' as const
const getDefectStatusName = (status: string) => status
const getDefectSeverityType = (_severity: string) => 'danger' as const
const getDefectSeverityName = (severity: string) => severity
const getDefectPriorityType = (_priority: string) => 'warning' as const
const getDefectPriorityName = (priority: string) => priority

// 格式化负责人显示（只显示姓名）
const formatAssigneeDisplay = (assigneeId?: string, assigneeName?: string) => {
  if (!assigneeId) return '未分配'
  
  // 只显示姓名
  if (assigneeName) {
    return assigneeName
  }
  return '未分配'
}

// 加载默认关联的需求信息
const loadDefaultRequirement = async (requirementId: string) => {
  if (!requirementId) return
  
  try {
    const requirement = await requirementAPI.getRequirementById(requirementId)
    if (requirement) {
      // 检查是否已经存在，避免重复添加
      const exists = selectedRequirements.value.some(item => item.id === requirement.id)
      if (!exists) {
        let assigneeDisplay = '未分配'
        
        // 如果有负责人ID，获取完整的用户信息（包括头衔和姓名）
        if (requirement.assignee_id) {
          try {
            const userResponse = await getUserDetail(requirement.assignee_id)
            // 处理不同的响应格式
            let user = null
            if (userResponse && userResponse.data) {
              if (userResponse.data.success && userResponse.data.data) {
                user = userResponse.data.data
              } else if (userResponse.data.id) {
                user = userResponse.data
              }
            }
            
            if (user) {
              assigneeDisplay = formatAssigneeDisplay(
                requirement.assignee_id,
                user.name || user.username
              )
            } else {
              // 如果获取用户信息失败，使用需求中的 assignee_name
              assigneeDisplay = requirement.assignee_name || '未分配'
            }
          } catch (error) {
            console.error('获取用户信息失败:', error)
            // 如果获取用户信息失败，使用需求中的 assignee_name
            assigneeDisplay = requirement.assignee_name || '未分配'
          }
        }
        
        selectedRequirements.value.push({
          id: requirement.id,
          title: requirement.title,
          status: requirement.status,
          priority: requirement.priority,
          assignee_id: requirement.assignee_id,
          assignee_name: assigneeDisplay
        })
      }
    }
  } catch (error) {
    console.error('加载需求详情失败:', error)
    // 不显示错误消息，因为这只是为了显示，不影响功能
  }
}

// Watchers
watch(
  () => props.visible,
  async (value) => {
    if (value) {
      resetForm()
      // resetForm 已经会设置 requirement_id，但为了确保在对话框打开时能正确设置，
      // 这里再次确保 requirement_id 被设置为 defaultRequirementId
      if (props.defaultRequirementId) {
        formData.requirement_id = props.defaultRequirementId
        // 加载需求详情并添加到已选择列表中
        await loadDefaultRequirement(props.defaultRequirementId)
      }
    }
  }
)

watch(
  () => props.currentUserId,
  (userId) => {
    if (userId && !formData.reporter_id) {
      formData.reporter_id = userId
    }
  },
  { immediate: true }
)

watch(
  () => props.defaultProjectId,
  (value) => {
    if (value && !formData.project_id) {
      formData.project_id = value
    }
  },
  { immediate: true }
)

watch(
  () => [props.visible, props.defaultRequirementId] as const,
  async ([visible, requirementId]) => {
    // 当对话框打开且 defaultRequirementId 有值时，更新表单数据
    // 这样可以处理对话框打开后 defaultRequirementId 才变化的情况
    if (visible && requirementId) {
      formData.requirement_id = requirementId
      // 加载需求详情并添加到已选择列表中
      await loadDefaultRequirement(requirementId)
    }
  }
)
</script>

<style scoped lang="scss">
.create-task-dialog {
  :deep(.el-dialog) {
    max-height: 90vh;
    display: flex;
    flex-direction: column;
  }

  :deep(.el-dialog__header) {
    padding: 0;
    border-bottom: 1px solid #ebeef5;
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }

  :deep(.el-dialog__title) {
    display: none;
  }

  :deep(.el-dialog__body) {
    padding: 24px;
    flex: 1;
    min-height: 0;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }
}

.create-task {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0;
}

.detail-body {
  display: flex;
  gap: 24px;
  flex: 1;
  min-height: 0;
  overflow: hidden;
  align-items: flex-start;
}

.primary-column {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
  overflow-y: auto;
  padding-right: 8px;
  min-height: 0;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
  }
}

.detail-header {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 16px;
}

.header-top {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.status-tags {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.title-section {
  margin-bottom: 8px;
}

.title-input {
  width: 100%;
}

.section-card {
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 12px;
  padding: 0;
  display: flex;
  flex-direction: column;
  gap: 16px;
  box-shadow: 0 4px 12px rgba(31, 56, 88, 0.05);
}

.tabs-card {
  padding: 0;
}

.content-tabs {
  :deep(.el-tabs__header) {
    margin: 0;
    padding: 0 24px;
    border-bottom: 1px solid #ebeef5;
  }

  :deep(.el-tabs__content) {
    padding: 0;
  }
  
  :deep(.el-tab-pane) {
    padding: 24px;
  }
}

.tab-content-wrapper {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.associations-card {
  padding: 0;
}

.associations-header {
  padding: 20px 24px;
  border-bottom: 1px solid #ebeef5;
}

.associations-title {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
}

.associations-content {
  padding: 24px;
}

.side-column {
  width: 400px;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  padding: 24px;
  position: sticky;
  top: 0;
  align-self: flex-start;
  gap: 16px;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
  }

  &::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
  }
}

.info-card {
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 12px;
  padding: 18px 20px;
  display: flex;
  flex-direction: column;
  gap: 14px;
  box-shadow: 0 4px 12px rgba(31, 56, 88, 0.05);
}

.info-card-title {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
}

.info-form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-label {
  color: #909399;
  font-size: 13px;
}

.required {
  color: #f56c6c;
  margin-left: 4px;
}

.field-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
  font-weight: 500;
}

.field-error {
  :deep(.el-input__wrapper) {
    border-color: #f56c6c !important;
    box-shadow: 0 0 0 1px #f56c6c inset !important;
  }
  
  :deep(.el-select__wrapper) {
    border-color: #f56c6c !important;
    box-shadow: 0 0 0 1px #f56c6c inset !important;
  }
}

.error-message {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 4px;
  line-height: 1.5;
}

.dialog-header-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 20px 24px;
  position: relative;
}

.dialog-header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  line-height: 1;
}

.dialog-header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-left: auto;
}

.association-sub-tabs {
  :deep(.el-tabs__header) {
    margin: 0;
  }

  :deep(.el-tabs__content) {
    padding: 0;
  }
}

.sub-tab-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 16px;
}

.tab-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 12px;
  border-bottom: 1px solid #ebeef5;

  .header-info {
    .item-count {
      font-size: 15px;
      font-weight: 600;
      color: #303133;
    }
  }

  .header-actions {
    display: flex;
    gap: 8px;
  }
}

.items-list {
  min-height: 300px;
}

.parent-info-display {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: #f0f9ff;
  border: 1px solid #b3d8ff;
  border-radius: 6px;
  
  .el-tag {
    display: flex;
    align-items: center;
    gap: 4px;
  }
  
  .parent-hint {
    font-size: 13px;
    color: #909399;
  }
}

@media (max-width: 992px) {
  .detail-body {
    flex-direction: column;
  }

  .side-column {
    width: 100%;
    border-left: none;
    border-top: 1px solid #ebeef5;
    padding-left: 0;
    padding-top: 16px;
  }
}
</style>
